package com.example.wujinapi.comm;

import com.alibaba.druid.util.StringUtils;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

@Component
public class RSAutil {

    @Autowired
    private RedisUtils redisUtils;

    private static String privateKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCtTkyrFSI6WAYizeMiJggdq+oNrZSAfsEv5697t+1MVej8cMX09+hYW1WTdFeDsnBSZgN/YaPO/Hv6MAtDO2FihrI08mworFz3Ya2MAngCP9BnOHLZ4paLSWXos11AMLa059WeGH4Vbn4sQ/tHtEo+rK4T3K3W7jCj6/WR0mtjLwIDAQAB";
    private static String publicKey="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAK1OTKsVIjpYBiLN4yImCB2r6g2tlIB+wS/nr3u37UxV6PxwxfT36FhbVZN0V4OycFJmA39ho878e/owC0M7YWKGsjTybCisXPdhrYwCeAI/0Gc4ctnilotJZeizXUAwtrTn1Z4YfhVufixD+0e0Sj6srhPcrdbuMKPr9ZHSa2MvAgMBAAECgYEAjCEWjvLcpS5Nb9DoCdGUmGFMM9kZjThwfoqocrHKdwG0DIInHidhwCfBryPQK1WZypZf15ycdh3jJO25/ZfC6jH1xEOcboiQ6S2JdzBe+PQD+gT1jY4VZnAsylFJf/bmHlxvDhY8h4JLVE6AeoU1DteSr44ssUIPdtumf3w9WsECQQDVWT2P/4Adp+XdXw/QuaQsC9G5sU/T9VO/YRUVjdZZrWdJzYm1uSnMYAor/49Qc/h0LF9oZYmYKlhUXNVnQZhhAkEAz/PAM+6qPlTnUhSOzdyaa+GKdiAET/qhruv874mKlSfM0yREHCWEh93lrYruO6yNsAhudB3yUPGXCFw90ElljwJBAKLK2G3DIKgAUCZtfezfakTts9cEVAxA2uliE6uBsfh1lyW6fwS5yAoZkklmVJ2oEAHdReOr7qS8Uu/0ciW66KECQBjgb/3Gb1dFkOagzvSRj2eYc5ft/JYUxYLHeFqveYSeXkJj9EHpuxEF2pQIKre4zLpiR9RcQMCuJgM6BasFHMECQAOVZj5V9EDQDDO9vHE22h+McJHhRYEPR0xu3XVR7265TRiEfp2KrQu36qGwVs4ByXAoRD0afrklnDnoosooDI4=";
    private static Map<String, String> keyMap = new HashMap<String, String>();  //用于封装随机产生的公钥与私钥

    /**
     * 随机生成密钥对
     * @throws NoSuchAlgorithmException
     */
    public static void genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(1024,new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        // 将公钥和私钥保存到Map
        keyMap.put("publicKey",publicKeyString);  //0表示公钥
        keyMap.put("privateKey",privateKeyString);  //1表示私钥
        System.out.println("公钥:"+publicKeyString);
        System.out.println("=================");
        System.out.println("私钥:"+privateKeyString);
    }
    /**
     * RSA公钥加密
     *
     * @param str
     *            加密字符串
     * @param publicKey
     *            公钥
     * @return 密文
     * @throws Exception
     *             加密过程中的异常信息
     */
    public static String encrypt(String str) throws Exception{
       // System.out.println("平台公钥"+H5pay.PlateformPublickKey);
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey); //H5pay.PlateformPublickKey
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param str
     *            加密字符串
     * @param privateKey
     *            私钥
     * @return 铭文
     * @throws Exception
     *             解密过程中的异常信息
     */
    public static String decrypt(String str) throws Exception{
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey); //H5pay.PrivateKey
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }


    /**
     * 根据sid 获取openid / sessionKey
     */
    public String getFromSid(String sid,String flag) throws Exception {
        try{
            String sessionid= decrypt(sid);
            if(StringUtils.equals(flag,"sessionId")){
                return sessionid;
            }
            if(StringUtils.equals(flag,"openid")){
                return redisUtils.get("openid_"+sessionid);
            }
            if(StringUtils.equals(flag,"sessionKey")){
                return redisUtils.get("key_"+sessionid);
            }
            if(StringUtils.equals(flag,"token")){
                return redisUtils.get("token_"+sessionid);
            }
        }catch (Exception e) {
            System.out.println(e.getStackTrace());
            return "";
        }
        return "";
    }



}//Class End
